import { createSlice, PayloadAction } from '@reduxjs/toolkit';

export interface Risk {
  id: string;
  opportunityId: string;
  title: string;
  description: string;
  level: 'low' | 'medium' | 'high';
  category: 'technical' | 'commercial' | 'operational' | 'financial' | 'legal';
  impact: number; // 1-10
  probability: number; // 1-10
  status: 'open' | 'mitigating' | 'closed';
  mitigation: string;
  owner: string;
  reporter: string;
  reportedAt: string;
  updatedAt: string;
  dueDate?: string;
  resolution?: string;
  resolvedAt?: string;
  comments: Array<{
    id: string;
    content: string;
    author: string;
    createdAt: string;
  }>;
}

export interface RiskState {
  risks: Risk[];
  currentRisk: Risk | null;
  loading: boolean;
  error: string | null;
  filters: {
    level: string[];
    category: string[];
    status: string[];
    opportunityId?: string;
  };
  pagination: {
    page: number;
    pageSize: number;
    total: number;
  };
}

const initialState: RiskState = {
  risks: [],
  currentRisk: null,
  loading: false,
  error: null,
  filters: {
    level: [],
    category: [],
    status: [],
  },
  pagination: {
    page: 1,
    pageSize: 20,
    total: 0,
  },
};

const riskSlice = createSlice({
  name: 'risk',
  initialState,
  reducers: {
    setLoading: (state, action: PayloadAction<boolean>) => {
      state.loading = action.payload;
    },
    setError: (state, action: PayloadAction<string | null>) => {
      state.error = action.payload;
    },
    setRisks: (state, action: PayloadAction<Risk[]>) => {
      state.risks = action.payload;
    },
    addRisk: (state, action: PayloadAction<Risk>) => {
      state.risks.unshift(action.payload);
    },
    updateRisk: (state, action: PayloadAction<Risk>) => {
      const index = state.risks.findIndex(risk => risk.id === action.payload.id);
      if (index !== -1) {
        state.risks[index] = action.payload;
      }
      if (state.currentRisk && state.currentRisk.id === action.payload.id) {
        state.currentRisk = action.payload;
      }
    },
    deleteRisk: (state, action: PayloadAction<string>) => {
      state.risks = state.risks.filter(risk => risk.id !== action.payload);
      if (state.currentRisk && state.currentRisk.id === action.payload) {
        state.currentRisk = null;
      }
    },
    setCurrentRisk: (state, action: PayloadAction<Risk | null>) => {
      state.currentRisk = action.payload;
    },
    addComment: (state, action: PayloadAction<{ riskId: string; comment: Risk['comments'][0] }>) => {
      const risk = state.risks.find(r => r.id === action.payload.riskId);
      if (risk) {
        risk.comments.push(action.payload.comment);
        risk.updatedAt = new Date().toISOString();
      }
      if (state.currentRisk && state.currentRisk.id === action.payload.riskId) {
        state.currentRisk.comments.push(action.payload.comment);
        state.currentRisk.updatedAt = new Date().toISOString();
      }
    },
    setFilters: (state, action: PayloadAction<Partial<RiskState['filters']>>) => {
      state.filters = { ...state.filters, ...action.payload };
    },
    setPagination: (state, action: PayloadAction<Partial<RiskState['pagination']>>) => {
      state.pagination = { ...state.pagination, ...action.payload };
    },
  },
});

export const {
  setLoading,
  setError,
  setRisks,
  addRisk,
  updateRisk,
  deleteRisk,
  setCurrentRisk,
  addComment,
  setFilters,
  setPagination,
} = riskSlice.actions;

export default riskSlice.reducer;
